<template>
  <el-pagination
    size="small"
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="pageSizes"
    :layout="layout"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script setup>
import { ref, watch } from "vue";

const props = defineProps({
  // 总条数
  total: {
    type: Number,
    required: true,
  },
  // 当前页码
  currentPage: {
    type: Number,
    default: 1,
  },
  // 每页显示条数
  pageSize: {
    type: Number,
    default: 10,
  },
  // 每页显示条数的选项
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100],
  },
  // 分页器布局
  layout: {
    type: String,
    default: "total, sizes, prev, pager, next, jumper",
  },
});

const emit = defineEmits(["update:currentPage", "update:pageSize", "page-change"]);

const currentPage = ref(props.currentPage);
const pageSize = ref(props.pageSize);

// 监听 props 的变化
watch(
  () => props.currentPage,
  (newVal) => {
    currentPage.value = newVal;
  }
);

watch(
  () => props.pageSize,
  (newVal) => {
    pageSize.value = newVal;
  }
);

// 每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  emit("update:pageSize", newSize);
  emit("page-change", { page: currentPage.value, size: newSize });
};

// 当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  emit("update:currentPage", newPage);
  emit("page-change", { page: newPage, size: pageSize.value });
};
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
